import { ImplementComponent } from "../ImplementComponent";
import { ServerComponentType } from "../Main";
import { RunComponent } from "../../../common/src/RunComponent";
import fs from "fs";
import * as cheerio from "cheerio";
import { DistStruct } from "../../../common/src/CreateDist";
import path from "path";

export class Configurable {
  private indexPath: string;
  constructor(
    com: ServerComponentType,
    im: ImplementComponent,
    runtime: RunComponent,
    dist: DistStruct
  ) {
    this.indexPath = path.join(dist.getRootPath(), "index.html");

    if (!com.config) return;

    const script = `\n<script>
        "use strict";
        ((win)=>{
            if(!win.lowCode.configArr)win.lowCode.configArr = [];
            const doc = win.document;
            function ${com.config.toString().replaceAll("DOMSELECTOR", "#" + runtime.getModuleId())}
            config(win.lowCode.configArr, window.lowCode.resources);
        })(window)
    </script>`;

    const $ = cheerio.load(fs.readFileSync(this.indexPath).toString());

    $("body").append(script);

    fs.writeFileSync(this.indexPath, $.html());
  }
  // public applyChange() {
  //   const indexStr = fs.readFileSync(this.indexPath).toString();
  //   const $ = cheerio.load(indexStr);
  //   $("body").append(`<script src="dev/dev.js"></script>`);

  //   fs.writeFileSync(this.indexPath, $.html());
  // }
}
